package com.sevenluo.netty.learn.common;

import com.google.gson.Gson;
import io.netty.buffer.ByteBuf;
import lombok.Data;

import java.nio.charset.StandardCharsets;

/**
 * @author: 程序员七哥
 * @date: 2022-01-25
 * @description:
 */
@Data
public abstract class Message<T extends MessageBody> {

    private MessageHeader messageHeader;

    private T messageBody;


    public void encode(ByteBuf byteBuf) {
        byteBuf.writeInt(messageHeader.getVersion());
        byteBuf.writeLong(messageHeader.getStreamId());
        byteBuf.writeInt(messageHeader.getOpCode());
        byteBuf.writeBytes(new Gson().toJson(messageBody).getBytes(StandardCharsets.UTF_8));
    }

    /**
     * 根据操作类型反序列化消息体
     * @param opCode
     * @return
     */
    public abstract Class<T> getMessageBodyDecodeClass(int opCode);

    /**
     * 方法封装 this 的使用很重要
     * @param msg
     */
    public void decode(ByteBuf msg) {
        int version = msg.readInt();
        long streamId = msg.readLong();
        int opCode = msg.readInt();

        MessageHeader messageHeader = new MessageHeader();
        messageHeader.setVersion(version);
        messageHeader.setStreamId(streamId);
        messageHeader.setOpCode(opCode);

        this.messageHeader = messageHeader;

        Class<T> bodyClass = getMessageBodyDecodeClass(opCode);

        T body = new Gson().fromJson(msg.toString(StandardCharsets.UTF_8),bodyClass);
        this.messageBody = body;

    }

}
